package cn.hh.redis.aspect;

import cn.hh.redis.annotation.CheckSmsCode;
import cn.hh.redis.util.RedisCache;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author huangh
 * @date 2021/11/30
 * @Description:
 */
@Aspect
@Component
public class WebAsepect {

    @Autowired
    private RedisCache redisCache;

    // 配置织入点
    @Pointcut("@annotation(cn.hh.redis.annotation.CheckSmsCode)")
    public void logPointCut()
    {
    }

    /*@Before(value = "logPointCut()")
    public  void before(JoinPoint joinPoint) {
        System.out.println("aop before.....");


    }*/

    /**
     * 环绕
     * @param point
     * @return
     * @throws Throwable
     */
    @Around(value = "logPointCut()")
    public  Object around(ProceedingJoinPoint point) throws Throwable {

        //在AOP中获取request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //获取response
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        /*
          localhost:8080/sms/sendSms?flag=1
          flag=1 返回22222
          flag=2 返回原始

         */
        System.out.println("aop around.....");
        /*
        Object[] objs = point.getArgs();
        Map<String,Object> param = (LinkedHashMap<String, Object>) objs[1];
        String flag = StrUtil.toString(param.get("flag"));
        if("1".equals(flag)){
            return "222222";
        }*/
        boolean flag = Boolean.parseBoolean(redisCache.getCacheObject("smsCheck"));
        if(!flag){
            return "请先验证短信验证码";
        }
        redisCache.deleteObject("smsCheck");

        return point.proceed();

    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    /*@AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
    {
        System.out.println("aop doAfterReturning.....");
        handleLog(joinPoint, null, jsonResult);
    }*/

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e)
    {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult)
    {
        try
        {
            // 获得注解
            CheckSmsCode checkSms = getAnnotationLog(joinPoint);
            if (checkSms == null)
            {
                return;
            }

            if (e != null)
            {
                System.out.println("no ");
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();



            // 处理设置注解上的参数
            //getControllerMethodDescription(joinPoint, checkSms);
            // 保存数据库
        }
        catch (Exception exp)
        {
            // 记录本地异常日志
           // log.error("==前置通知异常==");
            //log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param checkSms 日志
     * @param operLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, CheckSmsCode checkSms) throws Exception
    {




        // 获取参数的信息，传入到数据库中。
        setRequestValue(joinPoint);

    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint) throws Exception
    {
        String params = argsArrayToString(joinPoint.getArgs());
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private CheckSmsCode getAnnotationLog(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(CheckSmsCode.class);
        }
        return null;
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray)
    {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0)
        {
            for (int i = 0; i < paramsArray.length; i++)
            {
                if (!isFilterObject(paramsArray[i]))
                {
                    Object jsonObj = JSON.toJSON(paramsArray[i]);
                    params += jsonObj.toString() + " ";
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    public boolean isFilterObject(final Object o)
    {
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }
}
